#include <sstream>
#include "buram_test.h"

namespace igslib
{
    FileBuRAM::FileBuRAM()
    {
        name = "/data/data/buram";
        offset = 0;
        memset(ram,0,sizeof(ram));

        fp = fopen(GetName().c_str(),"rb");
        if (fp)
        {
            size_t rb = fread(ram,sizeof(ram),1,fp);
            if (rb == 0)
            {
                std::stringstream ss;
                ss << "Read length shortage." << rb;
                throw_igslib_exception(ss.str());
            }
            fclose(fp);
        }
        else
        {
            fp = fopen(GetName().c_str(),"wb");
            if (fp == NULL)
            {
                std::stringstream ss;
                ss << "Can't write file(" << GetName().c_str() << ").";
                throw_igslib_exception(ss.str());
            }
            else
            {
                size_t wbl = fwrite(ram,sizeof(ram),1,fp);
                if (wbl == 0)
                {
                    std::stringstream ss;
                    ss << "Write length shortage." << sizeof(ram) << "/"<< wbl ;
                    throw_igslib_exception(ss.str());
                }
                fclose(fp);
            }
        }
    }

    void FileBuRAM::Flush()
    {
        rewind(fp);
        for(auto& each:blocks)
        {
            fwrite(each.addr,each.size,1,fp);
        }
        fflush(fp);
    }
    FileBuRAM::~FileBuRAM()
    {
        for(auto& each:blocks)
        {
            free(each.addr);
        }
        fclose(fp);
    }
    void* FileBuRAM::BindBlock(int size)
    {
        void* rtn = nullptr;

        if (size < 0)
        {
            return rtn;
        }

        if (offset >= GetSize())
        {
            return rtn;
        }

        rtn = (void*)&ram[offset];
        offset += size;

        return rtn;
    }
}
